#!/bin/bash

#python版本升级

py_ver(){
  local t1 t2 t3
  t1=$(python -V)
  t2="${t1#*Python}"
  t3=${t2// /}
  old_ver=${t3:0:3}
#  return "$old_ver"
}

#下载解压编译安装
download_install() {
  mkdir /usr/python
  cd /usr/python || exit
  local tarFile='Python-3.9.5.tar.xz'
  wget -O $tarFile https://www.python.org/ftp/python/3.9.5/Python-3.9.5.tar.xz

  # 热知识之什么都不做可以只写个冒号
  if test -e $tarFile; then
    :
  else
    #疑似下载有点失败了
    echo '下载Python源码失败'
    exit
  fi
  tar -xvf $tarFile
  local sourceDir='Python-3.9.5'
  cd $sourceDir || exit
  ./configure --prefix=/usr/python --enable-shared CFLAGS=-fPIC
  make && make install
}

#修改软连接，添加动态库目录
chg_dir() {
  mv /usr/bin/python /usr/bin/python"$old_ver".bk
  ln -s /usr/python/bin/python3.9 /usr/bin/python
  ln -s /usr/python/bin/pip3 /usr/bin/pip

  cd /etc/ld.so.conf.d && touch python.conf
  echo '/usr/python/lib' >python.conf
  ldconfig
}

#配置pipe
config_pipe() {
  local file
  file='/root/.pip/pip.conf'
  if test -e $file; then
    rm -rf /root/.pip
  fi
  cd /root/ && mkdir .pip && cd .pip && touch pip.conf
  cat << -e > $file
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
-e

  pip install --upgrade pip
}

adapt_yum(){
#修改yum、urlgrabber-ext-down文件中的第一行为#!/usr/bin/python2.7
#语法按照sed4.sh中的写法。注意#!似乎是特殊字符，sed匹配不到
sed -in "s/\/usr\/bin\/python/\/usr\/bin\/python$old_ver/" /usr/bin/yum
sed -in "s/\/usr\/bin\/python/\/usr\/bin\/python$old_ver/" /usr/libexec/urlgrabber-ext-down
}

py_ver
download_install
chg_dir
config_pipe
adapt_yum